import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  SearchOutlined,
  UndoOutlined,
  OrderedListOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Modal,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormSelect, FormListActionType } from '@ant-design/pro-form';
// import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/configLinksCategoryForm';
import LinksForm from './components/addLinksForm';
import { ADD_LINK, CONFIG_LINK_CATEGORY, EDIT_LINK } from './components/consts';
import AddLinksForm from './components/addLinksForm';
import ConfigLinksCategoryForm from './components/configLinksCategoryForm';
import {
  changeLinkOrder,
  deleteLinkById,
  getLinkList,
  getLinkTypeList,
  insertLink,
  updateLink,
} from '@/services/linkManager';
import '@/assets/css/index.less';
import moment from 'moment';

const handleAddLink = async (fields: any) => {
  const hide = message.loading('正在添加');

  try {
    const res = await insertLink({ ...fields });
    hide();
    if(res.code == '0'){
      message.success('添加成功！')
      return true;
    }else{
      return false
    }
  } catch (error) {
    hide();
    message.error('添加失败，请重试！' + error.data.message);
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除多个节点
 *
 * @param selectedRows
 */

const UsefulLinks: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [modalVisible, handleModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formListActionRef = useRef<FormListActionType>();
  const [currentRow, setCurrentRow] = useState<API.WatcherList>();
  const [selectedRows, setSelectedRows] = useState<API.WatcherList[]>();
  const [formTarget, setFormTarget] = useState<string>();
  const [isOrder, setIsOrder] = useState(false);
  const [orderNum, setOrderNum] = useState(0);

  //初始化搜索区域
  const [form] = Form.useForm();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  useEffect(() => {
    queryData();
  }, [page, pageSize]);
  const handleEditLink = async (fields: any) => {
    const hide = message.loading('正在添加');

    try {
      await updateLink({ ...fields, id: currentRow && currentRow.id });
      hide();
      message.success('修改成功！');
      return true;
    } catch (error) {
      hide();
      message.error('修改失败，请重试！' + error.data.message);
      return false;
    }
  };
  const handleOrderOk = async () => {
    const params = {
      id: currentRow.id,
      pxh: orderNum,
    };
    const res = await changeLinkOrder(params);
    if (res.code == '0') {
      message.success('修改成功！');
      queryData();
    }
    setIsOrder(false);
  };

  const handleOrderCancel = () => {
    setIsOrder(false);
  };

  const onOrderChange = (e: any) => {
    setOrderNum(e.target.value);
  };
  const handleRemove = async (selectedRows: any) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      await deleteLinkById({
        id: selectedRows.id,
      });
      hide();
      if (actionRef.current) {
        actionRef.current.reload();
      }
      message.success('已删除！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败！');
      return false;
    }
  };
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const queryData = async () => {
    let values = form.getFieldsValue();
    const params = {
      page: page,
      pageSize: pageSize,
    };

    const msg = await getLinkList(params, values);
    setDataArray(msg.data.list);
    setPagination({ ...pagination, total: msg.data.total });
  };
  const clickOnSort = (record) => {
    setCurrentRow(record);
    setIsOrder(true);
  };
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
          onChange={() => queryData()}
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="网站名称" name="name">
                <Input placeholder="请输入网站名称" />
              </Form.Item>
            </Col>

            <Col span={8}>
              <ProFormSelect
                onChange={() => queryData()}
                // width="60%"
                // label="修改友情链接分类"
                name="type"
                // onChange = {selectLinksCategory}
                placeholder="请选择链接分类"
                request={async () => {
                  // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                  // 如果需要转化参数可以在这里进行修改
                  const msg = await getLinkTypeList();
                  let res = [];
                  msg.data.map((item) => {
                    let temp = {};
                    temp['label'] = item.name;
                    temp['value'] = item.name;
                    res.push(temp);
                  });
                  return res;
                }}
              />
            </Col>

            <Col
              span={6}
              offset={2}
              className="basic-search-form-submit-btn"
              style={{ paddingLeft: 120, display: 'flex' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  const columns: ProColumns<API.WatcherList>[] = [
    {
      title: '友情链接分类',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'linkType',
    },
    {
      title: '网站名称',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'linkName',
    },
    {
      title: '网站地址',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'linkAddress',
    },
    {
      title: '排序',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'pxh',
    },
    {
      title: '操作',
      // align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            handleModalVisible(true);
            setFormTarget(EDIT_LINK);
            setCurrentRow(record);
          }}
        >
          <Button type={"primary"} shape={'round'} icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleRemove(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
        <a key={3} onClick={() => clickOnSort(record)}>
          <Button  className={'buttonMargin'} shape={'round'} icon={<OrderedListOutlined />}>
            排序
          </Button>
        </a>,
      ],
    },
  ];

  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const modalDialogDisplay = () => {
    if (formTarget == ADD_LINK || formTarget == EDIT_LINK) {
      return (
        <AddLinksForm
          onSubmit={async (value) => {
            let success;
            if (formTarget == ADD_LINK) success = await handleAddLink(value);

            else if (formTarget == EDIT_LINK) success = await handleEditLink(value);
            if (success) {
              handleModalVisible(false);
              setCurrentRow({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
              setCurrentRow({});
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            if (!showDetail) {
              setCurrentRow({});
            }
          }}
          updateModalVisible={modalVisible}
          values={currentRow || {}}
          key={new Date().getTime()}
        />
      );
    } else if (formTarget == CONFIG_LINK_CATEGORY) {
      return (
        <ConfigLinksCategoryForm
          onSubmit={async (value) => {
            let success;

            // if(!currentRow){
            // success = await handleAdd(value);
            // }else{
            // value.id=currentRow.id;
            // success = await handleUpdate(value);
            // }
            if (success) {
              handleModalVisible(false);
              setCurrentRow(undefined);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            form.resetFields();
            queryData();
          }}
          handleVisible={handleModalVisible}
          updateModalVisible={modalVisible}
          values={currentRow || {}}
          key={new Date().getTime()}
        />
      );
    }
  };
  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        headerTitle="友情链接"
        actionRef={actionRef}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        search={false}
        dataSource={dataArray}
        pagination={pagination}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="default"
            key="default"
            onClick={() => {
              handleModalVisible(true);
              setFormTarget(CONFIG_LINK_CATEGORY);
            }}
          >
            <EditOutlined />
            设置友情链接分类
          </Button>,

          <Button
            type="default"
            key="default"
            onClick={() => {
              handleModalVisible(true);
              setFormTarget(ADD_LINK);
            }}
          >
            <PlusOutlined />
            添加友情链接
          </Button>,
        ]}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {modalDialogDisplay()}
      <Modal
        destroyOnClose
        title="排序"
        open={isOrder}
        onOk={handleOrderOk}
        onCancel={handleOrderCancel}
      >
        <Input placeholder="请输入排序!" onChange={onOrderChange} />
      </Modal>
    </PageContainer>
  );
};

export default UsefulLinks;
